package com.honey.compilation.sql.dml;

import java.util.ArrayList;
import java.util.List;

import com.honey.compilation.sql.SqlKeyWord;
import com.honey.compilation.sql.SqlScript;
import com.honey.core.builder.CharacterBuilder;
import com.honey.core.compiler.CompilationException;
import com.honey.core.compiler.IndentSpace;

/**
 * 联合查询. SQL 92中定义如下:<br />
 * 	<query expression> UNION [ ALL ] [ <corresponding spec> ] <query term>
 * 
 * @author Administrator
 *
 */
public class Union  extends AbstractUnion implements SqlScript{
	
	/** 查询语句 */
	private List<AbstractSelect> unions ;
	
	/** union all 字符串 */
	private static final char []UNIONALL=new char[]{
		'U',
		'N',
		'I',
		'O',
		'N',
		' ',
		'A',
		'L',
		'L',
		' '	 
	};
	
	/** union 字符串 */
	private static final char []UNION=new char[]{
		'U',
		'N',
		'I',
		'O',
		'N',
		' '	
	};
	
	/**
	 * 构造函数
	 */
	public Union(){
		this.unions = new ArrayList<AbstractSelect>();
	}
	/**
	 * 构造函数
	 * @param selects 查询语句
	 */
	public Union(AbstractSelect ...selects){
		this.unions = new ArrayList<AbstractSelect>();
		addSelect(selects);
	}
	
	/**
	 * 添加联合查询语句
	 * @param selects 查询语句
	 */
	public void addSelect(AbstractSelect ...selects){
		for(AbstractSelect select : selects ){
			if(select != null)
				unions.add(select);
		}
	}

	/*
	 * (non-Javadoc)
	 * @see com.honey.core.dom.sql.dml.AbstractUnion#compiledContent(int)
	 */
	@Override
	public CharacterBuilder compiledContent(int indentLevel) throws CompilationException {
		CharacterBuilder answer = super.compiledContent(indentLevel);
		boolean bool = false;
		boolean isUnionAll = super.isUnionAll();
        for (AbstractSelect select : unions) {
        	if (bool){
        		IndentSpace.newLine(answer);
            	IndentSpace.spaceIndent(answer, indentLevel);
            	answer.append(isUnionAll?UNIONALL:UNION);
            	IndentSpace.newLine(answer);
            }else{
            	bool = true;
            }
        	CharacterBuilder cb = select.compiledContent(indentLevel); 
        	answer.append(cb.delete(cb.length()-1));
         }    
         answer.append(SqlKeyWord.OPERATION_SEMICOLON);
		return answer;
	}
}
